package org.fin.minicat.request;

import java.io.IOException;
import java.net.URI;

public class Request {

  private RequestMethod method;

  private URI uri;


  public Request(String requestInfo) throws IOException {
    load(requestInfo);
  }

  /**
   * 根据请求头信息，读取其中的信息，并提取成属性
   * @param requestInfo 请求信息
   */
  private void load(String requestInfo) throws IOException {
    // 将请求信息按行切分
    String[] headerLines = requestInfo.split("\\r\\n");
    // 将请求行按空格切分
    String[] requestLine = headerLines[0].split(" ");

    switch (requestLine[0].toUpperCase()) {
      case "GET":
        method = RequestMethod.GET;
        break;
      case "POST":
        method = RequestMethod.POST;
        break;
      default:
        throw new RuntimeException("unkown request method");
    }

    String uriStr = requestLine[1];

    String protocol;
    if (requestLine[2].equals("HTTP/1.1") || requestLine[2].equals("HTTP/1.0")) {
      protocol = "http";
    } else {
      throw new RuntimeException("不支持http协议以外的请求");
    }

    String hostname = "";
    String port = "";
    for (int i = 1; i < headerLines.length; i++) {
      String headerLine = headerLines[i];
      if (headerLine.startsWith("Host")) {
        String[] hostAndPort = headerLine.substring(headerLine.indexOf(" ") + 1).split(":");
        hostname = hostAndPort[0];
        port = hostAndPort[1];
      }
    }

    String temp = protocol + "://" + hostname + ":" + port + uriStr;
    uri = URI.create(temp);
  }

  public RequestMethod getMethod() {
    return method;
  }

  public URI getUri() {
    return uri;
  }

  @Override
  public String toString() {
    return "Request{" +
        "method=" + method +
        ", uri='" + uri + '\'' +
        '}';
  }

}
